package com.webproject.controllers;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.webproject.model.bean.PatientBean;
import com.webproject.model.interfaces.Clinic;

// TODO: Auto-generated Javadoc
/**
 * Annotation-driven <em>MultiActionController</em> that handles all non-form
 * URL's.
 * 
 * @author Juergen Hoeller
 * @author Mark Fisher
 * @author Ken Krebs
 * @author Arjen Poutsma
 */
@Controller
public class FindPatientController {

	/** The clinic. */
	private final Clinic clinic;

	/**
	 * Instantiates a new find patient controller.
	 * 
	 * @param clinic
	 *            the clinic
	 */
	@Autowired
	public FindPatientController(Clinic clinic) {
		this.clinic = clinic;
	}

	/**
	 * Process submit.
	 * 
	 * @param patient
	 *            the patient
	 * @param result
	 *            the result
	 * @param model
	 *            the model
	 * @return the string
	 */
	@RequestMapping(value = "/patients", method = RequestMethod.GET)
	public String processSubmit(PatientBean patient, BindingResult result,
			Model model) {

		// allow parameterless GET request for /patients to return all records
		if (patient.getLastName() == null) {
			patient.setLastName(""); // empty string signifies broadest possible
										// search
		}

		if (patient.getName() == null) {
			patient.setName(""); // empty string signifies broadest possible
									// search
		}

		if (patient.getHistory() == null) {
			patient.setHistory(""); // empty string signifies broadest possible
									// search
		}

		// find patients by last name
		Collection<PatientBean> results = this.clinic.findPatients(patient);

		if (results.size() < 1) {
			// no patients found
			result.rejectValue("lastName", "notFound", "not found");
			model.addAttribute("patient", patient);
			return "patients/search";
		}
		// multiple patients found
		model.addAttribute("selections", results);
		return "patients/list";
	}

	/**
	 * Sets the allowed fields.
	 * 
	 * @param dataBinder
	 *            the new allowed fields
	 */
	@InitBinder
	public void setAllowedFields(WebDataBinder dataBinder) {
		dataBinder.setDisallowedFields("id");
	}

	/**
	 * Setup form.
	 * 
	 * @param model
	 *            the model
	 * @return the string
	 */
	@RequestMapping(value = "/patients/search", method = RequestMethod.GET)
	public String setupForm(Model model) {
		model.addAttribute("patient", new PatientBean());
		return "patients/search";
	}
}
